package com.dji.sample.common.util;
/**
 * @author 10587
 * @date 2022/9/8
 */

import org.modelmapper.ModelMapper;
import org.modelmapper.convention.MatchingStrategies;
import org.modelmapper.convention.NameTokenizers;
import org.springframework.util.Assert;

import java.lang.reflect.InvocationTargetException;

/**
 * @author yjt
 * @date 2022-09-08
 * @description:
 */
public class ConvertUtil {

    /**
     * 严格模式
     *
     * @param source
     * @param destinationType
     */
    public static void map(Object source, Object destinationType) {
        ModelMapper modelMapper = new ModelMapper();
        modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
        modelMapper.map(source, destinationType);
    }

    /**
     * 驼峰->驼峰
     *
     * @param source
     * @param destinationType
     */
    public static void mapCCToCC(Object source, Object destinationType) {
        ModelMapper modelMapper = getConvert();
        modelMapper.getConfiguration().setSourceNameTokenizer(NameTokenizers.CAMEL_CASE);
        modelMapper.getConfiguration().setDestinationNameTokenizer(NameTokenizers.CAMEL_CASE);
        modelMapper.map(source, destinationType);
    }


    /**
     * 转换器
     *
     * @return
     */
    public static ModelMapper getConvert() {
        ModelMapper modelMapper = new ModelMapper();
        modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
        return modelMapper;
    }

    /**
     * 转对象
     *
     * @param <T>
     * @return T
     */
    public <T> T convertTo(Class<T> t) {
        Assert.notNull(t, "参数不能为NULL");
        T result = null;
        try {
            result = t.getDeclaredConstructor().newInstance();
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            e.printStackTrace();
        }
        if (null == result) {
            throw new RuntimeException("转换异常");
        }
        ConvertUtil.getConvert().map(this, result);
        return result;
    }

}
